import traceback

import settings
from db.aiomysql_connector import AioMysqlClient
from logger_config import logger
from services.cache_service import CacheUtils
from apscheduler.schedulers.tornado import TornadoScheduler

from tasks.ws_scheduler_task import WsSchedulerTask


class InitFunc:
    async def init_func(self):
        await self.init_mysql()
        await self.create_task()

    async def init_mysql(self):
        try:
            # todo 本地测试
            connect_param = settings.local_mysql_config
            aiomysql_client = AioMysqlClient(**connect_param)
            await aiomysql_client.init_pool()
            CacheUtils.set('aiomysql_pool', aiomysql_client)
        except:
            logger.error(f'aiomysql init connect failed{traceback.format_exc()}')

    @classmethod
    async def create_task(cls):
        print("create task start")
        scheduler = TornadoScheduler()
        web_socket_task = WsSchedulerTask()
        # todo 当前测试用,时间间隔少,实际上时间60 * 14
        scheduler.add_job(web_socket_task.send_bom, 'interval', seconds=15, max_instances=1)
        scheduler.add_job(web_socket_task.send_ten_day_data, 'interval', seconds=18, max_instances=1)
        scheduler.add_job(web_socket_task.send_pass_rate, 'interval', seconds=8, max_instances=1)
        scheduler.add_job(web_socket_task.send_cur_day_issued_data, 'interval', seconds=9, max_instances=1)
        scheduler.add_job(web_socket_task.send_semi_finished_check_result, 'interval', seconds=11, max_instances=1)
        scheduler.add_job(web_socket_task.send_quality_monitor, 'interval', seconds=14, max_instances=1)
        scheduler.add_job(web_socket_task.send_total_quality_monitor, 'interval', seconds=17, max_instances=1)
        scheduler.add_job(web_socket_task.send_day_product_trend, 'interval', seconds=19, max_instances=1)
        scheduler.add_job(web_socket_task.send_alarm_data, 'interval', seconds=23, max_instances=1)
        scheduler.add_job(web_socket_task.send_digit_twin_unit, 'interval', seconds=10, max_instances=1)
        scheduler.add_job(web_socket_task.send_digit_status, 'interval', seconds=1, max_instances=1)

        scheduler.start()
